package com.example;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring4.SpringTemplateEngine;

import javax.mail.internet.MimeMessage;
import java.util.Locale;

@Service
public class MailServiceImpl implements MailService {
    private static final Logger LOGGER = LoggerFactory.getLogger(MailServiceImpl.class);

    @Autowired
    private SpringTemplateEngine templateEngine;

    @Autowired
    JavaMailSender sender;

    /**
     * https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/integration.html#mail-usage-mime
     *
     * @param message
     * @return
     */
    @Override
    public boolean send(MailMessage message) {
        // TODO 参数校验...
        try { //构造消息
            MimeMessage mimeMessage = buildMimeMessage(message);
            //发送
            sender.send(mimeMessage);
        } catch (Exception e) {
            LOGGER.error("send mail error", e);
            return false;
        }
        return true;
    }


//    @Override
//    public void sendSimpleMail(SimpleMailMessage message) {
//        sender.send(message);
//    }

    private MimeMessage buildMimeMessage(MailMessage message) throws Exception {
        MimeMessage mimeMessage = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        //主题
        helper.setSubject(message.getSubject());
        //发送者
        helper.setFrom(message.getFrom());
        //接受者
        helper.setTo(message.getToList().toArray(new String[0]));
        //抄送
        if (!CollectionUtils.isEmpty(message.getCopyList())) {
            helper.setCc(message.getCopyList().toArray(new String[0]));
        }
        Context context = new Context(Locale.CHINA);
        context.setVariables(message.getParamMap());
        //解析模版
        String content = templateEngine.process("emailTemplate", context);
//        Map<String, Object> model = new HashedMap();
//        model.put("username", "didi");
//        String text = VelocityEngineUtils.mergeTemplateIntoString(
//                velocityEngine, "emailTemplate.vm", "UTF-8", model);
        // String content = templateEngine.process("/templates/emailTemplate.vm", context);
        helper.setText(content, true);
        return mimeMessage;
    }

    @Override
    public void send(SimpleMailMessage message) {
        sender.send(message);
    }
}

